<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Shijue_task extends CI_Controller {

	public function __construct() {
		parent::__construct();
		
	}
	
	public function test_upload(){
		$this->load->model('oss_model');
		$object = 'testobject.doc';
		$filePath = 'D:\H2DATA\视觉中国\149630384044bea1375d673dacfa7038a2a6896ae6989300651.pdf';
		$url = $this->oss_model->upload_file($object, $filePath);
		echo $url;
	}

	public function test_delete(){
		$this->load->model('oss_model');
		$object = 'testobject.doc';
		$this->oss_model->deleteObject($object);
	}
	
	public function redis_demo(){
		$this->load->model('cache_model');
		$this->cache_model->set_info("wowo");
		
		$rs = $this->cache_model->get_info("wowo");
		
		print_r($rs);
	}

	public function start(){
		
		$this->load->model('queue_model');//队列
		$this->load->model('cache_model');//缓存
		if(false == ($json_keyword = $this->queue_model->get_shijue_task())){
			/*$json_keyword = '{
						    "pid": 100001,
						    "task_id": 123,
						    "clue_id": 456,
						    "url": "http://uuuuuuuuuuu1.com",
						    "pic_url": "http://mmbiz.qpic.cn/mmbiz_jpg/aHpkR8LlcibB45hiauWBctAq97wkD2SpKQtJC2bh2Ng4b9rK6bkeQSCOvuic2b73aVImblshYCNsib3qg1nlUWcdWA/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1",
						    "oss_pic_url": "http://ppppppppppp.com",
						    "width": "200",
						    "height": "300",
						    "size": "129458",
						    "is_cover": "0",
						    "img_format": "1",
						    "url_article_title": "abcdefghijk",
						    "url_article": "abcdefghijk",
						    "client_date": "2017-05-1100: 00: 00"
						}';*/
			
			admin_log("get_shijue_task is null", 'error_log');
			sleep(3);
			return false;		
		}
		
		//1、下载
		//2、获取属性
		$get_list = json_decode($json_keyword,true);
		$clue_key = md5("updateClue".$get_list['clue_id']);
		$clue_info = $this->cache_model->get_info($clue_key);

		if($clue_info != false){
			$msg = "cache, clue_id:".$get_list['clue_id'];
			
			admin_log($msg, 'clue_cache_log');

		}else{

			$b['task_id']=$get_list['task_id'];
			$b['clue_id']=$get_list['clue_id'];
			$b['clue_name']=$get_list['clue_name'];
			if($b['clue_name']){
				$clue_post = json_encode(array($b),true);
				$clue_url="http://182.92.98.172/Api/updateClue.php";
				echo $this->send_http_data($clue_url, array('data'=>$clue_post));
				echo "\n";	
				$msg = "success, clue_id:".$get_list['clue_id'];
			 	admin_log($msg, 'clue_name_success_log');
			 	//记录缓存
		 	 	$this->cache_model->set_info($clue_key);	
			}else{
				$msg = "null, clue_name is null clue_id:".$b['clue_id'];
			 	admin_log($msg, 'clue_name_null_log');
			}
		}
		
		$cache_key = md5($get_list['url'] . "#" . $get_list['pic_url'] . "#" . $get_list['is_cover']);
		
		$cache_info = $this->cache_model->get_info($cache_key);
		
		if($cache_info != false){
			$msg = "cache, task_id:".$get_list['task_id'].", clue_id:".$get_list['clue_id'].", pid:".$get_list['pid'].", pic_url:".$get_list['pic_url'];
			
			admin_log($msg, 'cache_log');
			return false;
		}
		
		// var_dump($get_list);die;
		$data = $this->getImage($get_list['pic_url']);
		
		if($data){
			//3、提交oss
			$this->load->model('oss_model');
			$object = $data['filename'];
			$filePath = $data['save_dir'];
			$oos_pic_url = $this->oss_model->upload_file($object, $filePath);
			unlink($data['save_dir']);
			if($oos_pic_url){

				unset($data['filename']);
				unset($data['save_dir']);
				unset($data['clue_name']);

				//4、拼接对象
				$data['oss_pic_url'] = $oos_pic_url;
				$data['pid'] =$get_list['pid'];
				$data['task_id'] =$get_list['task_id'];
				$data['clue_id'] =$get_list['clue_id'];
				$data['url'] =$get_list['url'];
				$data['pic_url'] =$get_list['pic_url'];
				$data['is_cover'] =$get_list['is_cover'];
				$data['url_article_title'] =$get_list['url_article_title'];
				$data['url_article'] =$get_list['url_article'];
				$data['client_date'] =$get_list['client_date'];


				// var_dump($data);die;
				//5、提交视觉中国
				$post = json_encode($data,true);
				$post ='['.$post.']';
				//var_dump($post);die;
				$url="http://182.92.98.172/Api/put_spider.php";
				//$this->send_http_data($url, array('resource'=>$post));
				$status = $this->send_http_data($url, array('resource'=>$post));
				if(strstr($status,'1009')){
					$this->send_http_data($url, array('resource'=>$post));
				}		
				admin_log($status, 'status_log');
				echo "\n";
				
				$msg = "send_http_data, task_id:".$data['task_id'].", clue_id:".$data['clue_id'].", pid:".$data['pid'].", pic_url:".$data['pic_url'];
				
	            admin_log($msg, 'task_success_log');
	            
	            //记录缓存
	            $this->cache_model->set_info($cache_key);
			}else{
				
				$rs = $this->queue_model->add_shijue_task_error($get_list);
				
				$msg = "start(): oos_pic_url = this->oss_model->upload_file( " .$object. ", " .$filePath. " ) : FAILED ; ";
	            admin_log($msg, 'error_log');
	            return false;
			}
			
		}else{

			$rs = $this->queue_model->add_shijue_task_error($get_list);
			
			$msg = "start(): data = this->getimagesize( " .$get_list['pic_url']. " ) : FAILED ; ";
            admin_log($msg, 'error_log');
            return false;

		}
			

	}


	public function test(){
		//$url = 'http://mmsns.qpic.cn/mmsns/vAjygJpArNSp8pVVcvp7d3VAQrRTelIKr0N2Bf0ISsoNiaLWtqUZU9A/0';
		//$url = 'http://img0.utuku.china.com/550x0/news/20170608/bd05f626-46a0-459c-8516-a7150f97826c.jpg';
		//$url = 'http://mmbiz.qpic.cn/mmbiz_jpg/7Ac0icgm9WAgyLUCQcDScZ9CSPn8ZtwY0jHcWKQg04VDQSHFeggky2viapRYibz0WGlw8tgH45rV6oDw0hRmFQD3A/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1';
		//$url = 'http://f200-9.bbs.hexun.com/_i/8/1/6/816ca573-8a14-4676-b892-f7434a4203cd.jpg';
		//$url = 'http://f200-8.bbs.hexun.com/_i/a/e/f/aef83826-a96c-44fe-aa58-1e4ebef3d21e.jpg';
		$url = 'https://img.pclady.com.cn/images/upload/upc/tx/pclady_capsule/1606/13/c0/22764894_1465801243541.jpg';
		$info = $this->getImage($url);
		
		//$info = $this->send_http_data($url);
		print_r($info);
	}
	
	/**
	 * @param string $url  下载图片的链接 
	 * 1.根据图片链接下载图片
	 * 2.返回图片属性
	 * @return array $data
	 *
	 */
	public function getImage($url){
		
		if(trim($url)==''){
			$msg = "img url : ".$url." is null ; ";
			admin_log($msg, 'error_log');
			return false;
		}
		
        // var_dump($url);
        echo $url;
        echo "\n";
        $img_type = @get_headers($url, 1);
		
        if(!isset($img_type['Content-Type']) || empty($img_type['Content-Type'])){
        	$img_type['Content-Type'] = "image/jpeg";
        }
        echo $img_type['Content-Type'];
        echo "\n";
		$arr=explode("/", $img_type['Content-Type']);
		
		$img_type = $arr[1];
		
		if( ! in_array($img_type, array('jpeg', 'jpg', 'png', 'gif', 'tif', 'bmp') ) ){
			$img_type = "jpg";
		}
		
		if($img_type =='jpeg'){
			$img_type = 'jpg';
		}
		
		$save_dir='./img/';
		$filename=time().rand(1,10000000000).".".$img_type;
		$data['filename'] = $filename;
		$data['save_dir'] = dirname(APPPATH).'/img/'.$filename;
		
		$data['img_format'] = str_replace(['jpg','png','gif','tif','bmp'], ['1','2','3','4','5'], $img_type);
		
		//创建保存目录
		if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
			$msg = "create dir : ".$save_dir." failed ; ";
			admin_log($msg, 'error_log');
			return false;
		}
		//sleep(1);	
		//$ch=curl_init();

		//curl_setopt($ch,CURLOPT_URL,$url);
		//curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		//curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
		//curl_setopt($ch,CURLOPT_TIMEOUT, 10);
		//$img=curl_exec($ch);
		$img=$this->send_http_data($url);
		//curl_close($ch);
		//var_dump($img);
		//sleep(1);
		if(empty($img)){
			
                        //$img = @file_get_contents($url);
                        //$fp2=@fopen($save_dir.$filename,'a');
                        //fwrite($fp2,$img);
                        //fclose($fp2);
                        //unset($img,$url);
                        //$filesize = filesize($data['save_dir']);
                        //$data['size'] = 100;
                        //$img_format = getimagesize($data['save_dir']);
                        //$data['width'] = 100;
                        //$data['height'] = 200;
                        return false;
                       
                }

		
		$fp2=@fopen($save_dir.$filename,'a');
		fwrite($fp2,$img);
		fclose($fp2);
		unset($img,$url);

		$filesize = filesize($data['save_dir']);
		$data['size'] = ceil($filesize/1024);
		$img_format = getimagesize($data['save_dir']);
		$data['width'] = $img_format[0];
		$data['height'] = $img_format[1];
		
		return $data;
	}



	public function send_http_data($url, $post = array(), $ip = "", $timeout = 10, $header = array(), $connecttimeout = 60) {

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

		if($post){
			if(is_array($post)){
				$post = http_build_query($post);
			}

			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		}

		if ($header){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		}
		
		if(!empty($ip)) {
			curl_setopt($ch, CURLOPT_PROXY, $ip);
			curl_setopt($ch, CURLOPT_PROXYTYPE , CURLPROXY_SOCKS5);
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "hongmai:soften.cn");
		}

		//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); 
		
		$rs = curl_exec($ch);
		$http_info = curl_getinfo($ch);

		curl_close($ch);
		if($http_info['http_code'] != 200 && $http_info['http_code'] != 302 ){
			return false;
		}
		return $rs;
	}




}